<template>
  <div class="app-container">
    <!-- 搜索和筛选区域 -->
    <el-card class="filter-container" shadow="never">
      <el-form :inline="true" :model="searchForm" ref="searchFormRef" size="small">
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable @keyup.enter="handleSearch" />
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="searchForm.role" placeholder="请选择角色" clearable>
            <el-option 
              v-for="item in roleOptions" 
              :key="item.name" 
              :label="item.displayName || item.name" 
              :value="item.name" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="部门">
          <el-select v-model="searchForm.departmentId" placeholder="请选择部门" clearable>
            <el-option 
              v-for="item in departmentOptions" 
              :key="item.id" 
              :label="item.name" 
              :value="item.id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" value="active" />
            <el-option label="禁用" value="inactive" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <h3>用户列表</h3>
          <div>
            <el-button 
              type="primary" 
              @click="handleCreate" 
              v-permission="'user:create'"
            >
              新增用户
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="userList"
        border
        style="width: 100%"
        row-key="id"
        @sort-change="handleSortChange"
      >
        <el-table-column prop="username" label="用户名" min-width="120" />
        <el-table-column prop="name" label="姓名" min-width="120" />
        <el-table-column prop="email" label="邮箱" min-width="180" />
        <el-table-column prop="role" label="角色" min-width="120">
          <template #default="scope">
            <el-tag>{{ scope.row.roleInfo?.displayName || scope.row.role }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="departmentName" label="部门" min-width="150" />
        <el-table-column prop="status" label="状态" min-width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 'active' ? 'success' : 'danger'">
              {{ scope.row.status === 'active' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" min-width="180" sortable="custom">
          <template #default="scope">
            {{ formatDateTime(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="280">
          <template #default="scope">
            <el-button
              type="primary"
              link
              size="small"
              @click="handleEdit(scope.row)"
              v-permission="'user:update'"
            >
              编辑
            </el-button>
            <el-button
              :type="scope.row.status === 'active' ? 'danger' : 'success'"
              link
              size="small"
              @click="handleToggleStatus(scope.row)"
              v-permission="'user:update'"
            >
              {{ scope.row.status === 'active' ? '禁用' : '启用' }}
            </el-button>
            <el-button
              type="warning"
              link
              size="small"
              @click="handleResetPassword(scope.row)"
              v-permission="'user:update'"
            >
              重置密码
            </el-button>
            <el-button
              type="danger"
              link
              size="small"
              @click="handleDelete(scope.row)"
              v-permission="'user:delete'"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          v-model:current-page="page"
          v-model:page-size="limit"
          @size-change="fetchUsers"
          @current-change="fetchUsers"
        />
      </div>
    </el-card>

    <!-- 重置密码对话框 -->
    <el-dialog
      title="重置密码"
      v-model="resetPasswordDialog.visible"
      width="500px"
    >
      <el-form :model="resetPasswordDialog.form" label-width="120px" ref="resetPasswordFormRef">
        <el-form-item label="新密码" prop="password">
          <el-input 
            v-model="resetPasswordDialog.form.password" 
            placeholder="请输入新密码" 
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input 
            v-model="resetPasswordDialog.form.confirmPassword" 
            placeholder="请再次输入新密码" 
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="resetPasswordDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="confirmResetPassword" :loading="resetPasswordDialog.loading">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { userAPI, roleAPI, departmentAPI } from '@/utils/api'
import { formatDateTime } from '@/utils/format'

const router = useRouter()

// 数据列表
const userList = ref([])
const loading = ref(false)
const total = ref(0)
const page = ref(1)
const limit = ref(20)
const sortBy = ref('createdAt')
const order = ref('desc')

// 下拉选项
const roleOptions = ref([])
const departmentOptions = ref([])

// 搜索表单
const searchFormRef = ref(null)
const searchForm = reactive({
  username: '',
  role: '',
  departmentId: '',
  status: ''
})

// 重置密码对话框
const resetPasswordDialog = reactive({
  visible: false,
  loading: false,
  userId: '',
  form: {
    password: '',
    confirmPassword: ''
  }
})

// 获取用户列表
const fetchUsers = async () => {
  loading.value = true
  try {
    const params = {
      page: page.value,
      limit: limit.value,
      sortBy: sortBy.value,
      order: order.value,
      ...searchForm
    }
    
    const res = await userAPI.getUsers(params)
    console.log('用户列表API响应:', res)
    
    // 处理不同的响应格式
    if (res.success) {
      // 直接返回了标准格式
      userList.value = res.data.users || []
      total.value = res.data.total || 0
    } else if (res.data && res.data.success) {
      // 包裹了一层data
      userList.value = res.data.data.users || []
      total.value = res.data.data.total || 0
    } else {
      ElMessage.error('获取用户列表失败：响应格式不正确')
      console.error('响应格式不正确:', res)
    }
  } catch (error) {
    console.error('获取用户列表失败', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 获取角色列表
const fetchRoles = async () => {
  try {
    const res = await roleAPI.getRoles()
    console.log('角色列表API响应:', res)
    
    // 处理不同的响应格式
    if (res.success) {
      roleOptions.value = res.data.roles || []
    } else if (res.data && res.data.success) {
      roleOptions.value = res.data.data.roles || []
    } else {
      console.error('获取角色列表失败：响应格式不正确', res)
    }
  } catch (error) {
    console.error('获取角色列表失败', error)
  }
}

// 获取部门列表
const fetchDepartments = async () => {
  try {
    const res = await departmentAPI.getDepartments()
    console.log('部门列表API响应:', res)
    
    // 处理不同的响应格式
    if (res.success) {
      departmentOptions.value = res.data.departments || []
    } else if (res.data && res.data.success) {
      departmentOptions.value = res.data.data.departments || []
    } else {
      console.error('获取部门列表失败：响应格式不正确', res)
    }
  } catch (error) {
    console.error('获取部门列表失败', error)
  }
}

// 搜索
const handleSearch = () => {
  page.value = 1
  fetchUsers()
}

// 重置搜索
const resetSearch = () => {
  searchFormRef.value.resetFields()
  page.value = 1
  fetchUsers()
}

// 排序变化
const handleSortChange = (column) => {
  if (column.prop) {
    sortBy.value = column.prop
    order.value = column.order === 'ascending' ? 'asc' : 'desc'
    fetchUsers()
  }
}

// 新增用户
const handleCreate = () => {
  router.push('/system/users/create')
}

// 编辑用户
const handleEdit = (row) => {
  router.push(`/system/users/edit/${row.id}`)
}

// 切换用户状态
const handleToggleStatus = (row) => {
  const newStatus = row.status === 'active' ? 'inactive' : 'active'
  const statusText = newStatus === 'active' ? '启用' : '禁用'
  const confirmMsg = `确定要${statusText}该用户吗？`
  
  ElMessageBox.confirm(confirmMsg, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await userAPI.updateUser(row.id, {
        status: newStatus
      })
      
      console.log('切换用户状态响应:', res)
      
      // 处理不同的响应格式
      let success = false
      
      if (res.success) {
        success = true
      } else if (res.data && res.data.success) {
        success = true
      }
      
      if (success) {
        ElMessage.success(`用户${statusText}成功`)
        fetchUsers()
      } else {
        const message = res.data?.message || res.message
        ElMessage.error(message || `用户${statusText}失败`)
      }
    } catch (error) {
      console.error(`用户${statusText}失败`, error)
      ElMessage.error(`用户${statusText}失败`)
    }
  }).catch(() => {})
}

// 重置密码
const handleResetPassword = (row) => {
  resetPasswordDialog.userId = row.id
  resetPasswordDialog.form.password = ''
  resetPasswordDialog.form.confirmPassword = ''
  resetPasswordDialog.visible = true
}

// 确认重置密码
const confirmResetPassword = async () => {
  // 验证两次密码是否一致
  if (resetPasswordDialog.form.password !== resetPasswordDialog.form.confirmPassword) {
    ElMessage.error('两次输入的密码不一致')
    return
  }
  
  resetPasswordDialog.loading = true
  try {
    const res = await userAPI.resetPassword(resetPasswordDialog.userId, {
      newPassword: resetPasswordDialog.form.password
    })
    
    console.log('重置密码响应:', res)
    
    // 处理不同的响应格式
    let success = false
    
    if (res.success) {
      success = true
    } else if (res.data && res.data.success) {
      success = true
    }
    
    if (success) {
      ElMessage.success('密码重置成功')
      resetPasswordDialog.visible = false
    } else {
      const message = res.data?.message || res.message
      ElMessage.error(message || '密码重置失败')
    }
  } catch (error) {
    console.error('密码重置失败', error)
    ElMessage.error('密码重置失败')
  } finally {
    resetPasswordDialog.loading = false
  }
}

// 删除用户
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该用户吗？删除后将无法恢复！', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await userAPI.deleteUser(row.id)
      
      console.log('删除用户响应:', res)
      
      // 处理不同的响应格式
      let success = false
      
      if (res.success) {
        success = true
      } else if (res.data && res.data.success) {
        success = true
      }
      
      if (success) {
        ElMessage.success('用户删除成功')
        fetchUsers()
      } else {
        const message = res.data?.message || res.message
        ElMessage.error(message || '用户删除失败')
      }
    } catch (error) {
      console.error('用户删除失败', error)
      ElMessage.error('用户删除失败')
    }
  }).catch(() => {})
}

// 生命周期钩子
onMounted(() => {
  fetchUsers()
  fetchRoles()
  fetchDepartments()
})
</script>

<style scoped>
.filter-container {
  margin-bottom: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 